package main

import (
	"math/rand"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

const keyRequestId = "requestId"

func main() {
	// 创建一个默认的Engine实例
	r := gin.Default()
	logger, err := zap.NewProduction()
	if err != nil {
		panic(err)
	}

	// middleware 相当于aop
	r.Use(func(c *gin.Context) {
		s := time.Now()

		c.Next()

		logger.Info("incoming request",
			zap.String("path", c.Request.URL.Path),
			zap.Int("status", c.Writer.Status()),
			zap.Duration("elapsed", time.Now().Sub(s)))
	}, func(c *gin.Context) {
		c.Set(keyRequestId, rand.Int())

		c.Next()
	})

	r.GET("/ping", func(c *gin.Context) {
		h := gin.H{
			"message": "pong",
		}
		if rid, exists := c.Get(keyRequestId); exists {
			h[keyRequestId] = rid
		}
		c.JSON(200, h)
	})

	r.GET("/hello", func(c *gin.Context) {
		c.String(http.StatusOK, "hello")
	})

	r.GET("/test", test)

	r.GET("/micheal", miceal)
	r.Run()
}

func test(c *gin.Context) {
	c.JSON(http.StatusOK, map[string]interface{}{
		"message": "自己写的map没有使用gin",
		"code":    200,
	})
}

type Micheal map[string]interface{}

func miceal(c *gin.Context) {
	c.JSON(http.StatusOK, Micheal{
		"message": "hello func",
	})
}
